﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Management;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using UtilZ.Dotnet.Ex.Log;
using UtilZ.Dotnet.WindowsDesktopEx.Base;
using UtilZ.Dotnet.WindowsDesktopEx.NativeMethod;

namespace DFWpfApp1
{
    /// <summary>
    /// TestLoger.xaml 的交互逻辑
    /// </summary>
    public partial class TestLoger : Window
    {
        public TestLoger()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            var redirectAppenderToUI = (RedirectAppender)Loger.GetAppenderByName(null, "RedirectToUI");
            if (redirectAppenderToUI != null)
            {
                redirectAppenderToUI.RedirectOuput += RedirectLogOutput;
            }
        }

        private void RedirectLogOutput(object sender, RedirectOuputArgs e)
        {
            logControl.AddLog(e.Item.Content, e.Item.Level);

            //string str;
            //try
            //{
            //    str = string.Format("{0} {1}", DateTime.Now, e.Item.Content);
            //}
            //catch (Exception ex)
            //{
            //    str = ex.Message;
            //}

            //logControl.AddLog(str, e.Item.Level);
        }


        private void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            Loger.Trace("Trace");
            Loger.Debug("Debug");
            Loger.Warn("Warn");

            ILogerCore logerCore = Loger.GetLoger(null);
            if (logerCore != null)
            {
                logerCore.Info("Info");
                logerCore.Error("Error");
                logerCore.Fatal("Fatal");
            }
        }

        private void btnSet_Click(object sender, RoutedEventArgs e)
        {

        }

        private void btnRemove_Click(object sender, RoutedEventArgs e)
        {

        }

        private void btnExpire_Click(object sender, RoutedEventArgs e)
        {
            
        }

        private void btnTest_Click(object sender, RoutedEventArgs e)
        {
            //bool ret = WindowHelper.IsNoResponse(17576);
            //GetWerfaultCrushProcessIdList();

            Process[] pros = Process.GetProcessesByName("DotnetWinFormApp");
            bool ret = WindowHelper.IsNoResponse(pros[0].MainWindowHandle);
            //+		Bounds	{X = 1165 Y = 607 Width = 451 Height = 332}	System.Drawing.Rectangle
            IReadOnlyList<WindowInfo> windowInfos = WindowHelper.FindWindows(t => { return t.Title != null && t.Title.Contains(pros[0].MainWindowTitle); });
        }

        private List<int> GetWerfaultCrushProcessIdList()
        {
            IReadOnlyList<WindowInfo> windowInfo = WindowHelper.FindWindows();
            //MainWindow (未响应)
            List<int> crushProcessIdList = null;
            const string WERFAULT_PROCESS_NAME = "werfault";//Werfault.exe进程名称
            Process[] werfaultProcess = Process.GetProcessesByName(WERFAULT_PROCESS_NAME);


            foreach (var werfaultProces in werfaultProcess)
            {


                //ProcessManager.
                var werfaultCheckProcessId = this.GetWerfaultProcessId(werfaultProces.Id);
                if (werfaultCheckProcessId <= 0 ||
                    crushProcessIdList != null && crushProcessIdList.Contains(werfaultCheckProcessId))
                {
                    continue;
                }

                if (crushProcessIdList == null)
                {
                    crushProcessIdList = new List<int>();
                }
                crushProcessIdList.Add(werfaultCheckProcessId);
            }

            return crushProcessIdList;
        }

        /// <summary>
        /// 获取进程命令行信息
        /// </summary>
        /// <param name="pId"></param>
        /// <returns></returns>
        private int GetWerfaultProcessId(int werfaultProcessId)
        {
            try
            {
                using (ManagementObjectSearcher search = new ManagementObjectSearcher($"select CommandLine from Win32_Process where ProcessId={werfaultProcessId}"))
                //using (ManagementObjectSearcher search = new ManagementObjectSearcher($"select CommandLine from Win32_Process"))
                {
                    using (ManagementObjectCollection moc = search.Get())
                    {
                        StringBuilder sb = new StringBuilder();
                        foreach (ManagementObject mo in moc)
                        {
                            sb.Clear();
                            foreach (var pro in mo.Properties)
                            {
                                sb.Append(pro.Name);
                                sb.Append(':');
                                sb.AppendLine(pro.Value == null ? "null" : pro.Value.ToString());
                            }
                            string str = sb.ToString();
                            //werfault.exe /h /shared Global\\409752f6ec4c49a7a9aaaf24be671079 /t 10084 /p 29732
                            string commandLine = mo["CommandLine"].ToString();
                            if (string.IsNullOrWhiteSpace(commandLine))
                            {
                                continue;
                            }

                            const string PRO_PARA = "/p";
                            int index = commandLine.IndexOf(PRO_PARA);
                            if (index >= 0)
                            {
                                string pidStr = commandLine.Substring(index + PRO_PARA.Length).Trim();
                                index = pidStr.IndexOf(' ');
                                if (index > 0)
                                {
                                    pidStr = pidStr.Substring(0, index).Trim();
                                }

                                int pid;
                                if (int.TryParse(pidStr, out pid))
                                {
                                    return pid;
                                }
                            }
                            break;
                        }
                    }
                }
            }
            catch (ManagementException)
            { }
            catch (System.Runtime.InteropServices.COMException)
            { }

            return -1;
        }
    }
}
